package org.example.Server.service.paper.Impl;


import org.example.Server.context.question.QsUpdateContext;
import org.example.Server.mapper.paper.PaperPersonalMapper;
import org.example.Server.mapper.question.QuestionMapper;
import org.example.Server.model.paper.*;
import org.example.Server.model.question.QSelect;
import org.example.Server.model.question.QandA;
import org.example.Server.model.question.Question;
import org.example.Server.service.paper.PaperPersonalService;
import org.example.Server.utils.ResultAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Service
public class PaperPersonalServiceImpl implements PaperPersonalService {
    @Autowired
    PaperPersonalMapper paperPersonalMapper;
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    QsUpdateContext qsUpdateContext;

    private final Double DEFAULT_SCORE = 5d;

    @Transactional(rollbackFor = Exception.class)
    public ResultAPI addPaperHeader(PaperHeader paperHeader) {
        //添加试卷头
        paperPersonalMapper.addPaperHeader(paperHeader, 1);
        //添加试卷题型
        paperPersonalMapper.addPaperQsType(paperHeader.getPaper_id());
        return ResultAPI.success(paperHeader);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultAPI addPaperQsBySelf(PaperQsDTO questionPaper) {
        try {
            //先把都有的题头写了
            questionMapper.insertQs(questionPaper, false);
            //添加题和试卷关系
            paperPersonalMapper.addPaperQs(questionPaper);
            //再到题各自特性
            if (questionPaper.getQs_type().equals("qna")) {
                questionMapper.insertQandA(questionPaper);
            } else {
                questionMapper.insertOption(questionPaper.getOptions());
                questionMapper.insertQSandOption(questionPaper);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("SQL operation failed", e);
        }
        return ResultAPI.success(questionPaper);
    }

    public ResultAPI addPaperQsByQuestionStore(PaperQsStoreDTO paperQsStoreDTO) {
        //拿到题目
        Integer techId = paperQsStoreDTO.getTech_id();
        Integer paperId = paperQsStoreDTO.getPaper_id();
        List<Integer> ids = paperQsStoreDTO.getQs_ids();
        List<Question> questionList = questionMapper.getQuestionByIds(ids);

        if (questionList == null || questionList.isEmpty()) {
            return ResultAPI.error("No questions found");
        }
        //批量增加
        CopyQses(questionList, techId, paperId);
        return ResultAPI.success();
    }

    public ResultAPI getPaperHeaderLsit(Integer techId, Integer directionId, Integer difficulty) {
        List<PaperHeader> paperHeaders = paperPersonalMapper.getPaperHeaderLsit(techId, directionId, difficulty);
        return ResultAPI.success(paperHeaders);
    }

    public ResultAPI getPaperById(Integer paperId) {
        PaperAll paperAll = new PaperAll();
        //先获得试卷头
        PaperHeader paperHeader = paperPersonalMapper.getPaperHeaderById(paperId);
        //再获得试卷题型-显示每一题内容（包括答案以及选项（选择题
        //获取题型map
        List<PaperFormat> qsFormatList = paperPersonalMapper.getPaperFormatById(paperId);
        //按照题型获取
        for (int i = 0; i < qsFormatList.size(); i++) {
            String qsType = qsFormatList.get(i).getQs_type();
            //分题型
            if (qsType.equals("qna")) {
                //问答题
                PaperQna qna = new PaperQna(qsFormatList.get(i));
                List<QandA> qnas = paperPersonalMapper.getPaperQandA(paperId);
                qna.setItems(qnas);

                if (qnas != null && !qnas.isEmpty()) {
                    paperAll.getPaperList().add(qna);
                }
            } else {
                //选择类的
                PaperSelect paperSelect = new PaperSelect(qsFormatList.get(i));
                List<QSelect> qSelects = paperPersonalMapper.getPaperQSelect(paperId, qsType);
                paperSelect.setItems(qSelects);

                if (qSelects != null && !qSelects.isEmpty()) {
                    paperAll.getPaperList().add(paperSelect);
                }
            }

        }
        paperAll.setPaperHeader(paperHeader);
        Collections.shuffle(paperAll.getPaperList());
        return ResultAPI.success(paperAll);
    }

    public ResultAPI updateQsformat(PaperFormat paperFormat) {
        Integer paperFormatId = paperFormat.getPaper_format_id();
        String formatContent = paperFormat.getFormat_content();
        paperPersonalMapper.updateQsformat(paperFormatId, formatContent);
        return ResultAPI.success();
    }

    public ResultAPI updateQsMaxscore(PaperQsUpdate paperQsUpdate) {
        Integer qsId = paperQsUpdate.getQs_id();
        Integer paperId = paperQsUpdate.getPaper_id();
        Double maxScore = paperQsUpdate.getMax_score();
        paperPersonalMapper.updatePaperQsMaxscore(qsId, paperId, maxScore);
        return ResultAPI.success();
    }

    public ResultAPI updatePaperQs(PaperQsUpdate paperQsUpdate) {
        Double maxScore = paperQsUpdate.getMax_score();
        Integer paperId = paperQsUpdate.getPaper_id();
        Integer qsId = paperQsUpdate.getQs_id();
        if (maxScore != null) {
            paperPersonalMapper.updatePaperQsMaxscore(qsId, paperId, maxScore);
        }
        //策略模式
//        QsUpdateContext qsUpdateContext=new QsUpdateContext();
        qsUpdateContext.QsUpdate(paperQsUpdate.getQuestion());
        return ResultAPI.success();
    }

    public ResultAPI getPaperSetting(Integer paperId) {
        PaperSetting paperSetting = paperPersonalMapper.getPaperSettingById(paperId);
        return ResultAPI.success(paperSetting);
    }

    public ResultAPI updatePaperSetting(PaperSetting paperSetting) {
        paperPersonalMapper.updatePaperSetting(paperSetting);
        return ResultAPI.success();
    }

    public ResultAPI deletePapers(List<Integer> ids) {
        paperPersonalMapper.deletePapers(ids);
        return ResultAPI.success();
    }

    /**
     * 删除试卷中的试题，但是因为试卷中的题目其实都是复制出来的
     * 所以好像只传qs也可以（那么就可以用删除试题的接口了）
     *
     * @param paper_qs_ids
     * @return
     */
    public ResultAPI deletePaperQs(List<Integer> paper_qs_ids) {
        List<Integer> qsIds = paperPersonalMapper.getQsIdByPaperQId(paper_qs_ids);
        paperPersonalMapper.deletePaperQs(paper_qs_ids);
        questionMapper.deleteQS(qsIds);
        return ResultAPI.success();
    }


    public void CopyQses(List<Question> questionList, Integer techId, Integer paperId) {
        //0.共有的先写了
        //先把都有的题头写了
        questionMapper.insertQses(questionList, techId, false);
        //添加题和试卷关系
        paperPersonalMapper.addPaperQses(questionList, paperId, DEFAULT_SCORE);
        //1.先把非选择类的过滤出来
        List<Question> QnaList = questionList.stream().filter(item -> item.getQs_type().equals("qna")).toList();
        //2.过滤出选择类的列表
        List<Question> QselList = questionList.stream().filter(item -> !item.getQs_type().equals("qna")).toList();
        //3.分别批量添加
        if (!QnaList.isEmpty()) {
            questionMapper.insertQandAs(QnaList);
        }
        if (!QselList.isEmpty()) {
            questionMapper.insertOptions(QselList);
            questionMapper.insertQSandOptions(QselList);
        }
    }
}
